package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.hc.constant.RedisConstant;
import org.jeecg.modules.hc.controller.dao.CompanyOrderDao;
import org.jeecg.modules.hc.controller.dao.CustomExportXlsDao;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcAfterSalesStateEnum;
import org.jeecg.modules.hc.enums.HcOrderStateEnum;
import org.jeecg.modules.hc.mapper.HcCompanyFoodOrderMapper;
import org.jeecg.modules.hc.mapper.HcCompanyInfoMapper;
import org.jeecg.modules.hc.mapper.HcCompanyMerchantSettingMapper;
import org.jeecg.modules.hc.mapper.HcCompanyPickupAddressMapper;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.utils.HcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @Description: 企业订餐订单
 * @Author: jeecg-boot
 * @Date:   2023-07-11
 * @Version: V1.0
 */
@Api(tags="企业订餐订单")
@RestController
@RequestMapping("/hc/hcCompanyFoodOrder")
@Slf4j
public class HcCompanyFoodOrderController extends JeecgController<HcCompanyFoodOrder, IHcCompanyFoodOrderService> {
	@Autowired
	private IHcCompanyFoodOrderService hcCompanyFoodOrderService;
	@Autowired
	private IHcCompanyInfoService  hcCompanyInfoService;
	@Autowired
	private IHcCompanyFoodListService hcCompanyFoodListService;
	@Autowired
	private IHcCompanyFoodSpecificationsService hcCompanyFoodSpecificationsService;
	@Autowired
	private IHcCompanyPickupAddressService hcCompanyPickupAddressService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IHcMerchantService hcMerchantService;
	@Autowired
	private IHcUserService hcUserService;
	@Autowired
	private IHcCompanyMerchantAfterSalesService companyMerchantAfterSalesService;

	@Resource
	private HcCompanyInfoMapper hcCompanyInfoMapper;

	@Resource
	private HcCompanyFoodOrderMapper hcCompanyFoodOrderMapper;

	@Resource
	private HcCompanyPickupAddressMapper hcCompanyPickupAddressMapper;
	@Resource
	private HcCompanyMerchantSettingMapper hcCompanyMerchantSettingMapper;
	@Resource
	private IHcCompanyDetailService hcCompanyDetailService;

	@ApiOperation("获取全局端商户订单统计信息")
	@GetMapping("/getGlobalMerchantOrderList")
	public Result<?> getGlobalMerchantOrderList(String companyId){
		return Result.ok(hcCompanyFoodOrderService.getGlobalMerchantOrderList(companyId));
	}

	@ApiOperation("获取全局端商户订单明细信息")
	@GetMapping("/getGlobalMerchantOrderDetailsList")
	public Result<?> getGlobalMerchantOrderDetailsList(@RequestParam(name = "merchantId")String merchantId, String companyId){
		return Result.ok(hcCompanyFoodOrderService.getGlobalMerchantOrderDetailsList(merchantId,companyId));
	}


	@ApiOperation("取消企业订餐订单")
	@GetMapping(value = "/cancelCompanyOrder")
	public Result<?> cancelCompanyOrder(@RequestParam(name = "orderNum")String orderNum) throws ParseException {
		List<HcCompanyFoodOrder> list = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum));

		List<String> companyIds = list.stream().map(HcCompanyFoodOrder::getCompanyId).distinct().collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(companyIds)){
			List<HcCompanyInfo> hcCompanyInfoList = hcCompanyInfoMapper.selectBatchIds(companyIds);
			hcCompanyInfoList.forEach(h -> {
				boolean b = HcUtils.nowBetweenHHmmss(h.getStartTime(), h.getEndTime());
				if (!b){
					throw  new JeecgBootException(h.getCompanyName()+"的订餐时间是"+h.getStartTime()+"-"+h.getEndTime()+",当前超过订餐时间范围，无法取消订单");
				}
			});
		}
		hcCompanyFoodOrderService.update(new HcCompanyFoodOrder().setState(HcOrderStateEnum.CANCELED),
				new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum,orderNum));
		return Result.OK("已取消");
	}

	@ApiOperation("获取商家有效订单")
	@GetMapping(value = "/getOrderListByMerchant")
	public Result<?> getOrderListByMerchant(HcCompanyFoodOrder param,
											@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
											@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {
		List<HcOrderMerchant> records = new ArrayList<>();
		Date parse = DateUtils.parseDate(param.getTimeBegin(), "yyyy年MM月dd日");
		String beginTime = "";
		String endTime = DateUtils.formatDate(parse, "yyyy-MM-dd") + " 18:00:00";

		Calendar instance = Calendar.getInstance();
		instance.setTime(parse);
		instance.add(Calendar.DAY_OF_MONTH, -1);
		beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";

		param.setTimeBegin(beginTime);
		param.setTimeEnd(endTime);

		LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,param.getMerchantId())
//								.eq(HcCompanyFoodOrder::getState,HcOrderStateEnum.COMPLETED)
								.eq(HcCompanyFoodOrder::getCompanyId,param.getCompanyId())
								.between(HcCompanyFoodOrder::getCreateTime,param.getTimeBegin(),param.getTimeEnd());
		List<String> orderNums = hcCompanyFoodOrderService.list(orderLambdaQueryWrapper).stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
		//根据订单区分
		for (String orderNum : orderNums) {
			HcOrderMerchant h = new HcOrderMerchant();
			List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
			List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum)
					.eq(HcCompanyFoodOrder::getMerchantId,param.getMerchantId()));
			//过滤掉取消的订单
			List<HcCompanyFoodOrder> foodOrderList = companyFoodOrders.stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(foodOrderList)){
				HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>()
						.eq(HcCompanyInfo::getId, foodOrderList.get(0).getCompanyId()));
				h.setCompanyName(hcCompanyInfo.getCompanyName());
				h.setRemarks(foodOrderList.get(0).getRemark());
				HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
				List<String> foodName = new ArrayList<>();
				//价格
				BigDecimal foodPrice = new BigDecimal(0);
				BigDecimal totalPrice = new BigDecimal(0);
				BigDecimal coopPrice = new BigDecimal(0);
				for (HcCompanyFoodOrder hcCompanyFoodOrder : foodOrderList) {

					h.setState(hcCompanyFoodOrder.getState());
					HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcCompanyFoodOrder.getMerchantId()));
					h.setStoreName(hcMerchant.getStoreName());
					h.setCreateTime(hcCompanyFoodOrder.getCreateTime());
					//地址
					String pickupAddressId = hcCompanyFoodOrder.getPickupAddressId();
					HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressMapper.selectOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
					h.setSupplyAddress(pickupAddress.getAddressCode());
					//取餐号
					h.setPickingSerialNo(hcCompanyFoodOrder.getPickingSerialNo());
					h.setNameTakingMeal(hcCompanyFoodOrder.getUsername());
					h.setSupplyAddress(pickupAddress.getAddressCode());
					JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
					JSONObject foodObject = foodInfo.getJSONObject("food");
					HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
					//商品数量
					int foodNum = (int) foodInfo.get("foodNum");
					// 获取 foodsSpecification 列表
					JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
					// 将 JSONArray 转换为 List<String>
					List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
					if (foodsSpecificationArray!=null){
						foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
						List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
						foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
					}else {
						foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
					}

					if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
						//获取门店价格
						HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
								.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
								.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
						if (null == companyMerchantSetting){
							companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
						}
						if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
							//获取企业合作价格
							foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
						}else {
							foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
						}
					}else {
						foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
					totalPrice = totalPrice.add(foodPrice);
				}
				hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
				h.setNameDishes(Joiner.on("+").join(foodName));
				hcOrderDetailedLists.add(hcOrderDetailed);
				h.setCommodityPrice(foodPrice);
//				h.setCommodityPrice(totalPrice);
				h.setTotalPrice(foodPrice);
				h.setHcOrderDetailedList(hcOrderDetailedLists);
				records.add(h);
			}
		}
		IPage<HcOrderMerchant> hcOrderMerchantPage = new Page<>();
		hcOrderMerchantPage.setRecords(records);
		hcOrderMerchantPage.setTotal(records.size());
		hcOrderMerchantPage.setCurrent(pageNo); // 设置当前页码为1
		hcOrderMerchantPage.setSize(pageSize); // 设置每页大小为合并后的记录数
		return Result.OK(hcOrderMerchantPage);
	}

	@ApiOperation("获取商户端订单页面的统计信息")
	@GetMapping("/getMerchantDataList")
	public Result<?> getMerchantDataList(@RequestParam(name = "merchantId")String merchantId,
										@RequestParam(name = "companyId")String companyId) throws ParseException {
		return Result.ok(hcCompanyFoodOrderService.getMerchantDataList(merchantId,companyId));
	}

	@ApiOperation("获取企业最新下单数据")
	@GetMapping("/getCompanyOrderLatest")
	public Result<?> getCompanyOrderLatest(@RequestParam(name = "companyId")String companyId) throws ParseException {
		return Result.ok(hcCompanyFoodOrderService.getCompanyOrderLatest(companyId));
	}


	@ApiOperation("获取商户端订单页面的统计信息")
	@GetMapping("/getOrderStatistics")
	public Result<?> getOrderStatistics(@RequestParam(name = "merchantId")String merchantId,
										@RequestParam(name = "companyId")String companyId) {
		return Result.ok(hcCompanyFoodOrderService.getOrderStatistics(merchantId,companyId));
	}

	/**
	 * 企业订餐订单-获取商户订单
	 *
	 * @return
	 */
	@ApiOperation(value="企业订餐订单-获取商户企业订单", notes="企业订餐订单-获取商户企业订单")
	@GetMapping(value = "/queryMerchantPageList")
	public Result<IPage<HcOrderMerchant>> queryMerchantPageList(HcCompanyFoodOrder companyFoodOrder,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		List<HcOrderMerchant> records = new ArrayList<>();
		LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,companyFoodOrder.getMerchantId())
				.eq(HcCompanyFoodOrder::getCompanyId,companyFoodOrder.getCompanyId())
				.eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED);
		List<String> orderNumList = hcCompanyFoodOrderService.list(orderLambdaQueryWrapper)
				.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
		List<String> orderNums = new ArrayList<>();
		//不允许有售后的单
		for (String s : orderNumList) {
//			HcCompanyMerchantAfterSales companyMerchantAfterSales = companyMerchantAfterSalesService
//					.getOne(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
//							.eq(HcCompanyMerchantAfterSales::getOrderOrderNum, s)
//							.last("limit 1"));
//			if (null == companyMerchantAfterSales){
				orderNums.add(s);
//			}
		}
		//根据订单区分
		for (String orderNum : orderNums) {
			HcOrderMerchant h = new HcOrderMerchant();
			List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
			List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper
					.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
							.eq(HcCompanyFoodOrder::getOrderNum, orderNum)
							.eq(HcCompanyFoodOrder::getMerchantId,companyFoodOrder.getMerchantId()));
			HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>()
					.eq(HcCompanyInfo::getId, companyFoodOrders.get(0).getCompanyId()));
			h.setCompanyName(hcCompanyInfo.getCompanyName());
			h.setRemarks(companyFoodOrders.get(0).getRemark());
			HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
			List<String> foodName = new ArrayList<>();
			//价格
			BigDecimal foodPrice = new BigDecimal(0);
			BigDecimal cooparetionPrice = new BigDecimal(0);
			for (HcCompanyFoodOrder hcCompanyFoodOrder : companyFoodOrders) {
				h.setState(hcCompanyFoodOrder.getState());
				HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcCompanyFoodOrder.getMerchantId()));
				h.setStoreName(hcMerchant.getStoreName());
				h.setCreateTime(hcCompanyFoodOrder.getCreateTime());
				//地址
				String pickupAddressId = hcCompanyFoodOrder.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressMapper.selectOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				h.setSupplyAddress(pickupAddress.getAddressCode());
				//取餐号
				h.setPickingSerialNo(hcCompanyFoodOrder.getPickingSerialNo());
				h.setNameTakingMeal(hcCompanyFoodOrder.getUsername());
				h.setSupplyAddress(pickupAddress.getAddressCode());
				JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				// 获取 foodsSpecification 列表
				JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
				// 将 JSONArray 转换为 List<String>
				List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
				if (foodsSpecificationArray!=null){
					foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
					List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
					foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
				}else {
					foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
				}
				if (hcCompanyFoodList.getCooperatePrice() ==null || hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (null == companyMerchantSetting){
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
						cooparetionPrice = cooparetionPrice.add(hcCompanyInfo.getMerchantPrice());
					}else {
						foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
						cooparetionPrice = cooparetionPrice.add(companyMerchantSetting.getMerchantCooperatePrice());
					}
				}else {
					foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
					cooparetionPrice = cooparetionPrice.add(hcCompanyFoodList.getCooperatePrice());
				}
			}
//			hcOrderDetailed.setCommodityQuantity(foodNum);
			hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
			h.setNameDishes(Joiner.on("+").join(foodName));
			hcOrderDetailedLists.add(hcOrderDetailed);
			h.setCommodityPrice(cooparetionPrice);
			h.setTotalPrice(foodPrice);
			h.setHcOrderDetailedList(hcOrderDetailedLists);
			records.add(h);
		}
		IPage<HcOrderMerchant> hcOrderMerchantPage = new Page<>();
		hcOrderMerchantPage.setRecords(records);
		hcOrderMerchantPage.setTotal(records.size());
		hcOrderMerchantPage.setCurrent(pageNo); // 设置当前页码
		hcOrderMerchantPage.setSize(pageSize); // 设置每页大小为合并后的记录数
		return Result.OK(hcOrderMerchantPage);
	}

	/**
	 * 企业订餐订单-获取商户订单
	 *
	 * @return
	 */
	@ApiOperation(value="企业订餐订单-获取商户企业订单", notes="企业订餐订单-获取商户企业订单")
	@GetMapping(value = "/queryMerchantPageListNew")
	public Result<IPage<HcOrderMerchant>> queryMerchantPageListNew(HcCompanyFoodOrder companyFoodOrder,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		List<HcOrderMerchant> records = new ArrayList<>();
		LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,companyFoodOrder.getMerchantId())
				.eq(HcCompanyFoodOrder::getCompanyId,companyFoodOrder.getCompanyId())
				.eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED);
		List<String> orderNumList = hcCompanyFoodOrderService.list(orderLambdaQueryWrapper)
				.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
		//根据订单区分
		for (String orderNum : orderNumList) {
			List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
			List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper
					.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
							.eq(HcCompanyFoodOrder::getOrderNum, orderNum)
							.eq(HcCompanyFoodOrder::getMerchantId,companyFoodOrder.getMerchantId()));
			HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>()
					.eq(HcCompanyInfo::getId, companyFoodOrders.get(0).getCompanyId()));
			HcOrderMerchant h = new HcOrderMerchant();
			List<String> allFoodName = new ArrayList<>();
			for (HcCompanyFoodOrder hcCompanyFoodOrder : companyFoodOrders) {
				List<String> foodName = new ArrayList<>();
//				h.setId(hcCompanyFoodOrder.getId());
				h.setCompanyName(hcCompanyInfo.getCompanyName());
				h.setRemarks(hcCompanyFoodOrder.getRemark());
				HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
				h.setState(hcCompanyFoodOrder.getState());
				HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcCompanyFoodOrder.getMerchantId()));
				h.setStoreName(hcMerchant.getStoreName());
				h.setCreateTime(hcCompanyFoodOrder.getCreateTime());
				//地址
				String pickupAddressId = hcCompanyFoodOrder.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressMapper.selectOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				h.setSupplyAddress(pickupAddress.getAddressCode());
				//取餐号
				h.setPickingSerialNo(hcCompanyFoodOrder.getPickingSerialNo());
				h.setNameTakingMeal(hcCompanyFoodOrder.getUsername());
				h.setSupplyAddress(pickupAddress.getAddressCode());
				JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				// 获取 foodsSpecification 列表
				JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
				// 将 JSONArray 转换为 List<String>
				List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
				if (foodsSpecificationArray!=null){
					foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
					List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
					foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +")");
				}else {
					foodName.add(hcCompanyFoodList.getFoodName());
				}
				hcOrderDetailed.setCommodityQuantity(foodNum);
				hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
				hcOrderDetailed.setId(hcCompanyFoodOrder.getId());
				hcOrderDetailedLists.add(hcOrderDetailed);
				allFoodName.addAll(foodName);
			}
			h.setNameDishes(Joiner.on("+").join(allFoodName));
			h.setHcOrderDetailedList(hcOrderDetailedLists);
			records.add(h);
		}
		records.sort(new Comparator<HcOrderMerchant>() {
			@Override
			public int compare(HcOrderMerchant o1, HcOrderMerchant o2) {
				return o1.getNameDishes().compareTo(o2.getNameDishes());
			}
		});
		IPage<HcOrderMerchant> hcOrderMerchantPage = new Page<>();
		hcOrderMerchantPage.setRecords(records);
		hcOrderMerchantPage.setTotal(records.size());
		hcOrderMerchantPage.setCurrent(pageNo); // 设置当前页码
		hcOrderMerchantPage.setSize(pageSize); // 设置每页大小为合并后的记录数
		return Result.OK(hcOrderMerchantPage);
	}

	/**
	 * 企业订餐订单列表
	 *
	 * @param hcCompanyFoodOrder
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@ApiOperation(value="企业订餐订单列表", notes="企业订餐订单列表")
	@GetMapping(value = "/getPageList")
	public Result<?> getPageList(HcCompanyFoodOrder hcCompanyFoodOrder,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		LambdaQueryWrapper<HcCompanyFoodOrder> hcCompanyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyFoodOrder>();
		if (StringUtils.isNotBlank(hcCompanyFoodOrder.getTimeBegin()) && hcCompanyFoodOrder.getTimeBegin().length() == 16) {
			hcCompanyFoodOrder.setTimeBegin(hcCompanyFoodOrder.getTimeBegin() + ":00");
			hcCompanyFoodOrderLambdaQueryWrapper.ge(HcCompanyFoodOrder::getCreateTime,hcCompanyFoodOrder.getTimeBegin());
		}
		if (StringUtils.isNotBlank(hcCompanyFoodOrder.getTimeEnd()) && hcCompanyFoodOrder.getTimeEnd().length() == 16) {
			hcCompanyFoodOrder.setTimeEnd(hcCompanyFoodOrder.getTimeEnd() + ":00");
			hcCompanyFoodOrderLambdaQueryWrapper.le(HcCompanyFoodOrder::getCreateTime,hcCompanyFoodOrder.getTimeEnd());
		}
		if (StringUtils.isNotBlank(hcCompanyFoodOrder.getMerchantId())){
			hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,hcCompanyFoodOrder.getMerchantId());
		}
		if (StringUtils.isNotBlank(hcCompanyFoodOrder.getCompanyId())){
			hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getCompanyId,hcCompanyFoodOrder.getCompanyId());
		}
		if (StringUtils.isNotBlank(hcCompanyFoodOrder.getStoreName())){
			hcCompanyFoodOrderLambdaQueryWrapper.like(HcCompanyFoodOrder::getUsername,hcCompanyFoodOrder.getStoreName()).or()
					.like(HcCompanyFoodOrder::getPickingSerialNo,hcCompanyFoodOrder.getStoreName()).or()
					.like(HcCompanyFoodOrder::getFoodInfo,hcCompanyFoodOrder.getStoreName());
		}
		List<HcCompanyFoodOrder> list = hcCompanyFoodOrderService.list(hcCompanyFoodOrderLambdaQueryWrapper.orderByDesc(HcCompanyFoodOrder::getCreateTime));

		//获取企业订单信息
		List<String> orderNumList = list.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
		// 计算分页起始索引和结束索引
		int startIndex = (pageNo - 1) * pageSize;
		int endIndex = Math.min(startIndex + pageSize, orderNumList.size());
		// 截取需要的分页数据
		List<String> orderNums = orderNumList.subList(startIndex, endIndex);

		List<HcOrderMerchant> companyOrder = new ArrayList<>();
		for (String orderNum : orderNums) {
			HcOrderMerchant h = new HcOrderMerchant();
			h.setId(orderNum);
			List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
			LambdaQueryWrapper<HcCompanyFoodOrder> companyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyFoodOrder>()
					.eq(HcCompanyFoodOrder::getOrderNum, orderNum);
			if (StringUtils.isNotBlank(hcCompanyFoodOrder.getMerchantId())){
				companyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,hcCompanyFoodOrder.getMerchantId());
			}
			List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderService.list(companyFoodOrderLambdaQueryWrapper);
			HcCompanyInfo hcCompanyInfo = hcCompanyInfoService.getByCompId(companyFoodOrders.get(0).getCompanyId());
			h.setCompanyName(hcCompanyInfo.getCompanyName());

			HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
			List<String> foodName = new ArrayList<>();
			//价格
			BigDecimal foodPrice = new BigDecimal(0);
			//合作价格
			BigDecimal coopPrice = new BigDecimal(0);
			for (HcCompanyFoodOrder hcfo : companyFoodOrders) {
				h.setState(hcfo.getState());

				HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcfo.getMerchantId()));
				h.setStoreName(hcMerchant.getStoreName());
				h.setMerchantId(hcfo.getMerchantId());
				h.setCreateTime(hcfo.getCreateTime());
				//地址
				String pickupAddressId = hcfo.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				if (null != pickupAddress){
					h.setSupplyAddress(pickupAddress.getAddressCode());
					h.setSupplyAddress(pickupAddress.getAddressCode());
				}

				//取餐号
				h.setPickingSerialNo(hcfo.getPickingSerialNo());
				h.setNameTakingMeal(hcfo.getUsername());
				JSONObject foodInfo = JSONObject.parseObject(hcfo.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				// 获取 foodsSpecification 列表
				JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
				// 将 JSONArray 转换为 List<String>
				List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
				if (foodsSpecificationArray!=null){
					foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
					List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
					foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
				}else {
					foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
				}
				if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (null == companyMerchantSetting){
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
					}else {
						foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
				}else {
					foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
				}
				if (hcCompanyFoodList.getSalePrice()==null||hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (null == companyMerchantSetting){
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						coopPrice = coopPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
					}else {
						coopPrice = coopPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
					}
				}else {
					coopPrice = coopPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
				}
			}

			hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
			h.setNameDishes(Joiner.on("+").join(foodName));
			hcOrderDetailedLists.add(hcOrderDetailed);
			h.setCommodityPrice(foodPrice);
			h.setTotalPrice(coopPrice);
			h.setHcOrderDetailedList(hcOrderDetailedLists);
			companyOrder.add(h);
		}

		IPage<HcOrderMerchant> hcOrderMerchantIPage = new PageDTO<>();
		// 设置分页数据
		hcOrderMerchantIPage.setCurrent(pageNo);
		hcOrderMerchantIPage.setSize(pageSize);

		companyOrder.sort(new Comparator<HcOrderMerchant>() {
				@Override
				public int compare(HcOrderMerchant o1, HcOrderMerchant o2) {
					return o2.getCreateTime().compareTo(o1.getCreateTime());
				}
			});
			hcOrderMerchantIPage.setTotal(orderNumList.size());
			hcOrderMerchantIPage.setRecords(companyOrder);

		return Result.OK(hcOrderMerchantIPage);
	}


	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyFoodOrder
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@ApiOperation(value="企业订餐订单-分页列表查询", notes="企业订餐订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<HcMerchant>> queryPageList(HcCompanyFoodOrder hcCompanyFoodOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getUserId,hcCompanyFoodOrder.getUserId());
		List<HcCompanyFoodOrder> orders = hcCompanyFoodOrderService.list(orderLambdaQueryWrapper);
		List<String> orderNums = hcCompanyFoodOrderService.list(orderLambdaQueryWrapper).stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
		List<HcMerchant> merchantList = new ArrayList<>();
		//根据订单区分
		for (String orderNum : orderNums) {
			//当前订单下
			HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum).last("limit 1"));
			//当前订单的多个商品
			List<HcCompanyFoodOrder> collect = orders.stream().filter(o -> o.getOrderNum().equals(orderNum)).collect(Collectors.toList());
			Set<String> merchantIds = new HashSet<>();
			for (HcCompanyFoodOrder order : collect) {
				merchantIds.add(order.getMerchantId());
			}
			//售后
			LambdaQueryWrapper<HcCompanyMerchantAfterSales> companyMerchantAfterSalesLambdaQueryWrapper = new LambdaQueryWrapper<>();
			companyMerchantAfterSalesLambdaQueryWrapper.eq(HcCompanyMerchantAfterSales::getOrderOrderNum,orderNum).last("limit 1");
			HcCompanyMerchantAfterSales merchantAfterSales = companyMerchantAfterSalesService.getOne(companyMerchantAfterSalesLambdaQueryWrapper);
			HcAfterSalesStateEnum companyOrderSate = null;
			String id = "";
			if (null != merchantAfterSales){
				companyOrderSate = merchantAfterSales.getState();
				id = merchantAfterSales.getId();
			}
			LambdaQueryWrapper<HcMerchant> hcMerchantLambdaQueryWrapper = new LambdaQueryWrapper<>();
			hcMerchantLambdaQueryWrapper.in(HcMerchant::getId,merchantIds);
			List<HcMerchant> merchants = hcMerchantService.list(hcMerchantLambdaQueryWrapper);
			for (HcMerchant merchant : merchants) {
				merchant.setCreateTime(companyFoodOrder.getCreateTime());
				List<HcCompanyFoodOrder> foods = collect.stream().filter(c -> c.getMerchantId().equals(merchant.getId())).collect(Collectors.toList());
				List<Map<String,Object>> res = new ArrayList<>();
				foods.forEach( f -> {
					Map<String,Object> objectMap = new HashMap<>();
					objectMap.put("companyOrderId",f.getId());
					objectMap.put("food",f.getFoodInfo());
					res.add(objectMap);
				});
				HcCompanyMerchantAfterSales afterSales = companyMerchantAfterSalesService.getOne(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
						.eq(HcCompanyMerchantAfterSales::getOrderOrderNum, orderNum));
				if (null!=afterSales){
					merchant.setCompanyOrderAfterSalesState(afterSales.getState());
				}
				merchant.setCompanyOrderDaos(res);
				//取餐地址
				String pickupAddressId = companyFoodOrder.getPickupAddressId();
				LambdaQueryWrapper<HcCompanyPickupAddress> companyPickupAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
				companyPickupAddressLambdaQueryWrapper.eq(HcCompanyPickupAddress::getId,pickupAddressId);
				HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressService.getOne(companyPickupAddressLambdaQueryWrapper);
				merchant.setPickupAddress(pickupAddress.getPickupAddress());
				merchant.setAddressCode(pickupAddress.getAddressCode());
				merchant.setPickingSerialNo(companyFoodOrder.getPickingSerialNo());
				merchant.setOrderState(companyFoodOrder.getState().getValue());
				merchant.setOrderNum(orderNum);
				merchant.setCompanyOrderAfterSalesState(companyOrderSate);
				merchant.setCompanyOrderAfterSalesId(id);
			}
			merchantList.addAll(merchants);
		}
		merchantList.sort(new Comparator<HcMerchant>() {
			@Override
			public int compare(HcMerchant o1, HcMerchant o2) {
				return o2.getCreateTime().compareTo(o1.getCreateTime());
			}
		});
		IPage<HcMerchant> mergedPage = new Page<>();
		mergedPage.setRecords(merchantList);
		mergedPage.setTotal(merchantList.size());
		mergedPage.setCurrent(pageNo); // 设置当前页码为1
		mergedPage.setSize(pageSize); // 设置每页大小为合并后的记录数
		return Result.OK(mergedPage);
	}

	/**
	 *   添加
	 *
	 * @param hcCompanyFoodOrder
	 * @return
	 */
	@AutoLog(value = "企业订餐订单-添加")
	@ApiOperation(value="企业订餐订单-添加", notes="企业订餐订单-添加")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> add(@RequestBody HcCompanyFoodOrder hcCompanyFoodOrder) {
		if (StringUtils.isEmpty(hcCompanyFoodOrder.getCompanyId())){
			throw new JeecgBootException("请选择公司点餐");
		}
		List<CompanyOrderDao> companyOrderDaos = hcCompanyFoodOrder.getCompanyOrderDaos();
		if (CollectionUtils.isEmpty(companyOrderDaos)) {
			throw new JeecgBootException("未选购菜品");
		}

		// 获取当前日期
		LocalDate today = LocalDate.now();
		// 获取今天的18:59:00
		LocalDateTime end = LocalDateTime.of(today, LocalTime.of(18, 59, 59));
		// 获取昨天的19:00:00
		LocalDateTime start = LocalDateTime.of(today.minusDays(1), LocalTime.of(19, 0, 0));
		// 格式化时间
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String endTime = end.format(formatter);
		String beginTime = start.format(formatter);

		LambdaQueryWrapper<HcCompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
		companyInfoLambdaQueryWrapper.eq(HcCompanyInfo::getId,hcCompanyFoodOrder.getCompanyId());
		HcCompanyInfo companyInfo = hcCompanyInfoService.getOne(companyInfoLambdaQueryWrapper);
		if (companyInfo.getIsOpenBlackPaper().equalsIgnoreCase("yes")){
			if (StringUtils.isNotBlank(companyInfo.getBlackPaper())){
				//判断是否存在黑名单
				if (companyInfo.getBlackPaper().contains(hcCompanyFoodOrder.getUsername())){
					throw new JeecgBootException("暂时无法点餐");
				}
			}
		}

		hcCompanyFoodOrder.setOrderNum(UuidUtils.getUUID());
		//判断是否开启一人一天点餐一次
		if (companyInfo.getIsLimitOrder().equalsIgnoreCase("yes")){
			//判断数量
			if (!CollectionUtils.isEmpty(companyOrderDaos)) {
				companyOrderDaos.forEach(c -> {
					if (c.getFoodNum()>1){
						//判断是否在白名单
						if (StringUtils.isBlank(companyInfo.getWhitePaper())||!companyInfo.getWhitePaper().contains(hcCompanyFoodOrder.getUsername())){
							throw new JeecgBootException("每人每天只能点餐一次,无法点餐");
						}
					}
				});
			}
			synchronized (this){
				/*
				当前下单时间是否在19：00钟之后
				是-> 开始时间是今天19：00 到 明天 19：00
				否 -> 开始时间是昨天19：00 到今天19：00
				 */
				LocalDateTime time19_00 = LocalDateTime.of(today, LocalTime.of(19, 0, 0));
				if (LocalDateTime.now().isAfter(time19_00)){
					// 获取今天的19:00:00
					start = time19_00;
					// 获取明天的18:59:59
					end = LocalDateTime.of(today.plusDays(1), LocalTime.of(18, 59, 59));
					beginTime = start.format(formatter);
					endTime = end.format(formatter);
				}
				//判断今天是否已经点餐
				LambdaQueryWrapper<HcCompanyFoodOrder> hcCompanyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
				hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getUsername,hcCompanyFoodOrder.getUsername())
						.ge(HcCompanyFoodOrder::getCreateTime,beginTime).le(HcCompanyFoodOrder::getCreateTime,endTime).last("limit 1");
				HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(hcCompanyFoodOrderLambdaQueryWrapper);
				if (null!=companyFoodOrder){
					if (!companyFoodOrder.getState().equals(HcOrderStateEnum.CANCELED)){
						if (companyInfo.getIsOpenWhitePaper().equalsIgnoreCase("yes")){
							//判断是否在白名单
							if (StringUtils.isBlank(companyInfo.getWhitePaper())||!companyInfo.getWhitePaper().contains(hcCompanyFoodOrder.getUsername())){
								throw new JeecgBootException("每人每天只能点餐一次,无法点餐");
							}
						}else {
							throw new JeecgBootException("每人每天只能点餐一次,无法点餐");
						}
					}
				}
			}
		}
		//获取取餐序号
		String redisKey = RedisConstant.HC_ORDER_NO + beginTime + endTime + "_" + hcCompanyFoodOrder.getCompanyId();
		int pickingSerialNo = 1;

		if (redisUtil.hasKey(redisKey)) {
			pickingSerialNo = (int) redisUtil.incr(redisKey, 1);
		} else {
			redisUtil.set(redisKey, 1, 60 * 60 * 24);
		}
		log.info("取餐序号：{}，Redis-key：{}", pickingSerialNo, redisKey);

		//获取企业详情details
		List<HcCompanyDetail> hcCompanyDetails = hcCompanyDetailService.list(
				new LambdaQueryWrapper<HcCompanyDetail>()
						.eq(HcCompanyDetail::getCompanyId,hcCompanyFoodOrder.getCompanyId())
						.orderByDesc(HcCompanyDetail::getCreateTime).last("limit 1"));
		HcCompanyDetail hcCompanyDetail = hcCompanyDetails.get(0);

		//根据菜品进行添加
		for (CompanyOrderDao companyOrderDao : companyOrderDaos) {
			hcCompanyFoodOrder.setId(UuidUtils.getUUID());

			//商户信息
			hcCompanyFoodOrder.setMerchantId(companyOrderDao.getMerchantId());
			// 在加锁的情况下修改食品数量
			synchronized (this) {
				//获取当前菜品的剩余数量
				LambdaQueryWrapper<HcCompanyFoodList> foodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
				foodListLambdaQueryWrapper.eq(HcCompanyFoodList::getCompanyId, hcCompanyFoodOrder.getCompanyId())
						.eq(HcCompanyFoodList::getId, companyOrderDao.getFoodsId());
				HcCompanyFoodList companyFoodList = hcCompanyFoodListService.getOne(foodListLambdaQueryWrapper);
				companyOrderDao.setFood(companyFoodList);
				//可购数量
				Integer buyedNum = companyFoodList.getBuyedNum() == null ? companyFoodList.getLimitNum() : companyFoodList.getBuyedNum();
				Integer limitNum = companyFoodList.getLimitNum();
				if (limitNum != -1) {
					if (buyedNum >= companyOrderDao.getFoodNum()) {
						Integer integer = hcCompanyFoodListService.updateBuyedNum(companyFoodList.getId(),companyOrderDao.getFoodNum());
						if (integer<=0){
							throw new JeecgBootException("*" + companyFoodList.getFoodName() + "*限购，数量不足或已售罄，请选择其他菜品");
						}
					} else {
						throw new JeecgBootException("*" + companyFoodList.getFoodName() + "*限购，数量不足或已售罄，请选择其他菜品");
					}
				}

				if (StringUtils.isNotBlank(companyOrderDao.getFoodsSpecificationId())) {
					List<String> specificationIds = Arrays.asList(companyOrderDao.getFoodsSpecificationId().split(","));
					List<HcCompanyFoodSpecifications> specifications = new ArrayList<>();
					for (String specificationId : specificationIds) {
						//查询当前这个规格
						LambdaQueryWrapper<HcCompanyFoodSpecifications> foodSpecificationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
						foodSpecificationsLambdaQueryWrapper.eq(HcCompanyFoodSpecifications::getId, specificationId);
						HcCompanyFoodSpecifications hcCompanyFoodSpecifications = hcCompanyFoodSpecificationsService.getOne(foodSpecificationsLambdaQueryWrapper);
						specifications.add(hcCompanyFoodSpecifications);
					}
					companyOrderDao.setFoodsSpecification(specifications);
				}

				//商品信息
				hcCompanyFoodOrder.setFoodInfo(JSON.toJSONString(companyOrderDao));
				hcCompanyFoodOrder.setPickingSerialNo(pickingSerialNo);
				//对应的菜单id
				hcCompanyFoodOrder.setDetailsId(hcCompanyDetail.getId());
				hcCompanyFoodOrderService.save(hcCompanyFoodOrder);
			}
		}

		return Result.OK("添加成功！");
	}


	/**
	 *  编辑
	 *
	 * @param hcCompanyFoodOrder
	 * @return
	 */
	@AutoLog(value = "企业订餐订单-编辑")
	@ApiOperation(value="企业订餐订单-编辑", notes="企业订餐订单-编辑")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HcCompanyFoodOrder hcCompanyFoodOrder) {
		hcCompanyFoodOrderService.updateById(hcCompanyFoodOrder);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业订餐订单-通过id删除")
	@ApiOperation(value="企业订餐订单-通过id删除", notes="企业订餐订单-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hcCompanyFoodOrderService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业订餐订单-批量删除")
	@ApiOperation(value="企业订餐订单-批量删除", notes="企业订餐订单-批量删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hcCompanyFoodOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "企业订餐订单-通过id查询")
	@ApiOperation(value="企业订餐订单-通过id查询", notes="企业订餐订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HcCompanyFoodOrder> queryById(@RequestParam(name="id",required=true) String id) {
		HcCompanyFoodOrder hcCompanyFoodOrder = hcCompanyFoodOrderService.getById(id);
		if(hcCompanyFoodOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hcCompanyFoodOrder);
	}

	 /**
	  * 自定义导出企业订餐订单
	  *
	  */
	 @ApiOperation(value="自定义导出企业订餐订单", notes="自定义导出企业订餐订单")
	 @PostMapping(value = "/customExportXls")
	 public Result<?> customExportXls(@RequestBody CustomExportXlsDao customExportXlsDao) throws IOException, ParseException {
		 return Result.OK("导出成功",hcCompanyFoodOrderService.customExportXls(customExportXlsDao));
	 }

	/**
	 * 导出excel
	 */
	//@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
	@ApiOperation("商家订单页面导出")
	@RequestMapping(value = "/exportXls")
	public String exportXls(String ids,String companyId) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> list = null;

		if (StringUtils.isNotBlank(ids)) {
			list = Arrays.asList(ids.split(","));
		}

		return hcCompanyFoodOrderService.exportXls(sysUser.getId(),companyId, list, "");
	}

	/**
	 * 全局页面导出excel
	 */
	//@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
	@ApiOperation("全局页面导出excel")
	@RequestMapping(value = "/exportXlsGlobalPage")
	public String exportXlsGlobalPage(String merchantId,String companyId) {
		return hcCompanyFoodOrderService.exportXls(merchantId,companyId,null, "");
	}

	/**
	 * 平台端导出订单
	 */
	//@RequiresPermissions("org.jeecg.modules:hc_order_merchant:exportXls")
	@ApiOperation("平台端导出订单")
	@RequestMapping(value = "/platformExportXls")
	public ModelAndView platformExportXls(HcCompanyFoodOrder param) {
		return hcCompanyFoodOrderService.platformExportXls(param);
	}


	/**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("hc_company_food_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCompanyFoodOrder.class);
    }

}
